package com.xingfly.service;

import com.xingfly.model.Role;
import com.xingfly.repository.RoleRepository;
import com.xingfly.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by SuperS on 21/05/2017.
 *
 * @author SuperS
 */
@Service
public class RoleService {
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private UserRepository userRepository;
    //查询用户角色根据用户的ID
    public List<Role> findRolesByUserId(Long uid) {
        return roleRepository.findRolesByUserId(uid);
    }

    //创建角色
    public Role save(Role role) {
        return roleRepository.save(role);
    }
    //查询角色列表根据用户id(返回的是用户的所有角色)
    public List<String> findRolesNameByUserId(Long id) {
        List<String> roleNames = new ArrayList<>();
        for (Role role : roleRepository.findRolesByUserId(id)) {
            roleNames.add(role.getRole());
        }
        return roleNames;
    }
    //删除此id的所有角色
    public boolean deleteAllByUserId(Long uid) {
        if (roleRepository.countRolesByUserId(uid) > 0) {
            roleRepository.removeRolesByUsersContains(userRepository.findOne(uid));
            return true;
        }
        return false;
    }
}
